#include <cstring>
#include <cstrings>

#include "XM_InetAddr.hh"

XM_NAMESPACE_BEGIN

InetAddr::InetAddr(uint16_t port, std::string ip)
{
    // use string.h memset
    ::memset(&addr__, 0, sizeof(addr__));
    addr__.sin_family = AF_INET;
    addr__.sin_port = ::htons(port); // local byte order covert to net byte order
    addr__.sin_addr.s_addr = ::inet_addr(ip.c_str());
}

#define IP_BUFFER_SIZE 64
std::string InetAddr::toIp() const
{
    char buf[IP_BUFFER_SIZE] = {0};
    ::inet_ntop(AF_INET, &addr__.sin_addr, 
        buf, sizeof(buf)
    );

    return buf;
}

std::string InetAddr::toIpPort() const
{
    // ip:port style
    char buf[IP_BUFFER_SIZE] = {0};
    ::inet_ntop(AF_INET, &addr__.sin_addr,
        buf, sizeof(buf)
    );

    size_t end = ::strlen(buf);
    uint16_t port = ::ntohs(addr__.sin_port);
    sprintf(buf + end, ":%u", port);

    return buf;
}

uint16_t InetAddr::toPort() const
{
    return ::ntohs(addr__.sin_port);
}

XM_NAMESPACE_END